package heven.holt.wan.android.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import dagger.hilt.android.AndroidEntryPoint
import heven.holt.library.base.BaseFragment
import heven.holt.library.extensions.registerHeader
import heven.holt.library.loading.LoadingStateView
import heven.holt.library.loading.extensions.setLoadingStateCommonDecorHeader
import heven.holt.library.paging.LoadStateFooterMoreAdapter
import heven.holt.wan.android.MainFragmentDirections
import heven.holt.wan.android.R
import heven.holt.wan.android.adapter.CoinRankAdapter
import heven.holt.wan.android.databinding.FragmentCoinRankBinding
import heven.holt.wan.android.loading.delegate.CommonTitleDelegate
import heven.holt.wan.android.viewmodel.CoinRankViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class CoinRankFragment : BaseFragment<FragmentCoinRankBinding>() {
    private lateinit var loadingStateView: LoadingStateView

    private val coinRankViewModel: CoinRankViewModel by viewModels()

    private val coinRankAdapter: CoinRankAdapter = CoinRankAdapter()

    override fun bindViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): FragmentCoinRankBinding = FragmentCoinRankBinding.inflate(inflater, container, false)

    override fun createDecorationView(): View {
        val commonTitleDelegate = CommonTitleDelegate(
            getString(R.string.title_coin_rank),
            CommonTitleDelegate.TYPE_COIN_RULE
        ) { view ->
            val url = "https://www.wanandroid.com/blog/show/2653"
            val direction = MainFragmentDirections.actionGlobalWebViewFragment(url)
            view.findNavController().navigate(direction)
        }
        loadingStateView =
            binding.root.setLoadingStateCommonDecorHeader(commonTitleDelegate)
        loadingStateView.showLoadingView()
        return loadingStateView.decorView
    }

    override fun initView() {
        binding.springView.registerHeader {
            onReload()
        }

        val concatAdapter =
            coinRankAdapter.withLoadStateFooter(LoadStateFooterMoreAdapter {
                coinRankAdapter.retry()
            })
        binding.recyclerView.adapter = concatAdapter
    }

    override fun initData() {
        coinRankViewModel.topRankMap.observe(viewLifecycleOwner) {
            loadingStateView.showContentView()
            binding.rankMap = it
        }

        lifecycleScope.launch {
            coinRankViewModel.flow.collect {
                binding.springView.onFinishFreshAndLoad()
                coinRankAdapter.submitData(it)
            }
        }
    }

    private fun onReload() {
        coinRankAdapter.refresh()
    }
}